const app = getApp()

/**
 * wx.request的封装
 * 使用方式： httpExt.get("admin/login", {}).then(res => {}).catch(err => {})
 * @param {*} url 请求地址
 * @param {*} method 请求类型
 * @param {*} data 请求参数
 * @param {*} options 接口配置
 * @ifstorage "" 是否缓存，默认不缓存
 */
const request = (url, method, data, options, ifstorage) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  return new Promise((resolve, reject) => {
    //先判断缓存
    wx.getStorage({
      key: url,
      success(res) {
        console.log("成功获取缓存！！");
        resolve(res.data);
        wx.hideLoading();
      },
      fail(err) {
        console.log("获取缓存失败，访问API！");
        // 访问接口
        wx.request({
          url: url,
          method: method || 'GET',
          dataType: 'json',
          data: method === 'GET' ? options.data : JSON.stringify(options.data),
          header: {
            'Content-Type': 'application/json; charset=UTF-8',
            // 'token': wx.getStorageSync("SSP_token")
          },
          success(res) {
            //根据具体接口定义成功标准
            if (res.statusCode == 200) {
              if (ifstorage) {
                wx.setStorageSync(url, res.data);
              }
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail(error) {
            reject(error)
          },
          complete: info => {
            wx.hideLoading()
          }
        });
      }
    })

  })
}

const get = (url, data = {}, ifstorage, options = {}) => {
  return request(url, 'GET', data, options, ifstorage)
}
const post = (url, data = {}, ifstorage, options = {}) => {
  return request(url, 'POST', data, options, ifstorage)
}
const put = (url, data = {}, ifstorage, options = {}) => {
  return request(url, 'PUT', data, options, ifstorage)
}
// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, { method: 'DELETE', data: options })
}

module.exports = {
  get,
  post,
  put,
  remove
}